export default {
  namespaced:true,
  
  state:()=>({
    cart:JSON.parse(uni.getStorageSync('cart')||"[]")
  })
  ,
  
  mutations:{
    addtoCart(state,goods){
      const findResult = state.cart.find(item=>item.goods_id === goods.goods_id)
      if(!findResult){
        state.cart.push(goods)
      }else {
        findResult.goods_count++
      }
      this.commit('m_cart/saveToStorage')
      console.log(state.cart)
    },
    saveToStorage(state) {
      uni.setStorageSync('cart',JSON.stringify(state.cart))
    },
    clickR(state,goods){
      const findResult = state.cart.find(item=> item.goods_id === goods.goods_id)
      findResult.goods_state = goods.goods_state
      this.commit('m_cart/saveToStorage')
    },
    addCount(state,goods){
      const findResult = state.cart.find(item=> item.goods_id === goods.goods_id)
      if(findResult) {
        findResult.goods_count = goods.goods_count
      }
      this.commit('m_cart/saveToStorage')
      console.log(findResult)
    },
    removeGoods(state,goods){
      state.cart = state.cart.filter(item=>item.goods_id!==goods.goods_id)
      this.commit('m_cart/saveToStorage')
    },
    updateAllState(state,check){
      state.cart.forEach(item => item.goods_state = check)
      this.commit('m_cart/saveToStorage')
    }
  },
  
  getters:{
    total(state){
      return state.cart.reduce((total,item) => total+= item.goods_count,0)
    },
    checkedCount(state){
      return state.cart.filter(item =>item.goods_state===true).reduce((a,item)=> a +=item.goods_count,0)
    },
    checkedGoodsAmount(state){
      return state.cart.filter(item => item.goods_state).reduce((total,item) => total+=item.goods_count * item.goods_price,0).toFixed(2)
    }
  }
}